<template>
	<div class="body_bg_w big_login smallscreen_login">
		<div class="loginbg">

			<div class="text" >BuildMost</div>
		</div>
		<div class="loginbox">
			<div class="logintilte">欢迎登录 BuildMost</div>
			<yd-tab v-model="tabNum" active-color="#333333" :callback="getTab">
				<yd-tab-panel label="邮箱登录">
					<div
						:class="['logininp', accounthint ? '' : 'mar_b80']"
						style="margin-top: 0.5rem"
					>
						<input
							type="text"
							v-model.trim="username"
							@focus="getacfocus"
							@keyup="checkemail"
							v-validate="'required||newemail'"
							name="主题"
							placeholder="请输入电子邮箱地址"
						/>
					</div>
					<div v-if="accounthint" class="color_red accounthint">
						{{ accounthint }}
					</div>
					<div class="logininp password">
						<input
							type="password"
							ref="password"
							v-model.trim="password"
							@focus="getpassfocus"
							name="主题"
							placeholder="请输入您的密码"
						/>
						<span v-if="eyestatus">
							<img
								v-if="passwordstatus"
								src="@/image/eyes_close.png"
								@click="seepassword"
							/>
							<img v-else src="@/image/eyes_open.png" @click="seepassword" />
						</span>
					</div>
					<div v-if="passwordhint" class="color_red passwordhint">
						{{ passwordhint }}
					</div>
				</yd-tab-panel>
				<yd-tab-panel label="手机号码登录">
					<div class="selectcountry general_input" @click="selcetcountry">
						<input
							placeholder="国家/地区代码"
							readonly
							v-model.trim="ncountryname"
						/>
						<span class="iconfont icon-next fr"></span>
					</div>
					<div class="general_input" style="display: flex; align-items: center">
						<span>+</span>
						<input
							class="maincode"
							v-model.trim="userPhonecode"
							@focus="getnumfocus2"
							name="area code"
							placeholder="国家/地区代码"
							oninput="if(value.length>5)value=value.slice(0,5)"
							v-validate="'required||numeric'"
							@blur="onCountryCode"
						/>

						<input
							v-model.trim="userPhone"
							@focus="getnumfocus2"
							placeholder="请输入您手机号码"
							oninput="if(value.length>15)value=value.slice(0,15)"
							name="Mobile Number"
							v-validate="'required||numeric'"
						/>
					</div>
					<div v-if="accounthint2" class="color_red accounthint">
						{{ accounthint2 }}
					</div>
					<div class="logininp password">
						<input
							type="password"
							ref="phonePassword"
							v-model.trim="phonePassword"
							@focus="getpassfocus2"
							name="Subject"
							style="padding: 0.23rem 0"
							placeholder="请输入您的密码"
						/>
						<span v-if="eyestatus">
							<img
								v-if="passwordstatus"
								src="@/image/eyes_close.png"
								@click="seepasswordPhone"
							/>
							<img
								v-else
								src="@/image/eyes_open.png"
								@click="seepasswordPhone"
							/>
						</span>
					</div>
					<div v-if="passwordhint2" class="color_red passwordhint">
						{{ passwordhint2 }}
					</div>
				</yd-tab-panel>
			</yd-tab>

			<div class="loginrow">
				<div class="inb">
					<yd-checkbox-group v-model="checkbox" size="18" color="#0099FF">
						<yd-checkbox val="1" shape="circle">记住账号</yd-checkbox>
					</yd-checkbox-group>
				</div>
				<!-- <router-link to="/changePassword"> -->
				<span class="fr color_blue2 forget" @click="showname = true"
					>忘记密码 ?</span
				>
				<!-- </router-link> -->
			</div>
			<div class="login_botn">
				<div class="text-center loginbtn">
					<div @click="login">登录</div>
				</div>
				<div class="clwe_word text-center regs">
					<span>没有账号 ? </span>
					<span>&nbsp;</span>
					<router-link :to="t ? '/identities?t=' + t : '/identities'">
						<div class="color_blue2">免费注册!</div>
					</router-link>
				</div>
				<div class="text-center back-home-text flex" >
					<span class="color_blue2" @click="navTo('/')">返回首页 ></span>
				</div>
			</div>
			<van-action-sheet
				v-model="showname"
				:actions="PaymentList"
				cancel-text="取消"
				@select="callbackFn"
			></van-action-sheet>
		</div>
		<!-- 禁用弹框 -->
		<!-- 冻结弹框 -->
		<div class="freeze-open" style="display: none">
			<van-popup :close-on-click-overlay="false">
				<div class="freeze-box">
					<h3>账户已禁用</h3>
					<p>账号已被冻结，无法进行登录</p>
					<div class="freeze-top">
						<span
							>您可以发送电子邮件至
							<span style="color: #007dee"> {{ emailadress }} </span>
							进行申诉。</span
						>
						<span
							style="color: #007dee"
							v-clipboard:copy="emailadress"
							v-clipboard:success="onCopy"
							v-clipboard:error="onError"
							>复制邮件地址</span
						>
					</div>
					<div class="freeze-cause">
						<p>冻结原因</p>
						<p>{{ freezedata.frozenType }}</p>
						<p>{{ freezedata.freezeTimeType }}</p>
					</div>
					<span class="closebtn" @click="closebtn">关闭</span>
				</div>
			</van-popup>
		</div>
		<div class="freeze-open">
			<van-popup v-model="show" :close-on-click-overlay="false">
				<div class="freeze-box">
					<h3>账号冻结</h3>
					<p class="conten">
						很遗憾，您的 Buildmost 账号因为 "{{ freezedata.frozenType }},{{
							freezedata.freezeTimeType
						}}"被冻结了，您无法再使用此账号登录。您可以发送邮件service@buildmost.com
						进行申诉。
					</p>
					<div class="Confirmbtn">
						<button @click="closebtn">确认</button>
					</div>
				</div>
			</van-popup>
		</div>
		<!-- end -->
	</div>
</template>

<script>
// import District from "../../public/searchcountry.json";
import { debounce } from "@/plugin/inputchange.js";
import { mapGetters, mapMutations } from "vuex";
import eventBus from '@/plugin/eventBus'

import Fuse from 'fuse.js'
export default {
	data() {
		return {
			showValue: true,
			// CountryList: District,
			tabNum: 0,
			userPhone: "",
			ncountryname: "",
			areaCodeCountry: "",
			userPhonecode: "",
			phonePassword: "",
			activeTab: "", //當前選擇的tab
			showname: false,
			username: "",
			checkbox: [],
			password: "",
			passwordstatus: true,
			eyestatus: false,
			accounthint: "",
			passwordhint: "",
			accounthint2: "",
			passwordhint2: "",
			PaymentList: [
				{
					name: "通过电子邮箱找回密码",
					value: "ROUTER_P_EMAIL",
				},
				{
					name: "通过手机号找回密码",
					value: "ROUTER_P_PHONE",
				},
			],
			show: false, //冻结
			emailadress: "service@buildmost.com",
			freezedata: "",
			t: null,
			csrf: "",
			formType: null
		};
	},
	components: {},
	computed: {
		...mapGetters(["CountryList"]),
	},
	beforeRouteEnter(to, from, next) {
		// this.fromurl = from;
		next();
	},
	beforeRouteLeave(to, from, next) {
		console.log(to)
		if (
			to.name != 'select_country'
		) {
			this.$parent.clearCache(this);
		}
		next();
	},
	methods: {
		...mapMutations({
				setUserMwnuLists: 'setUserMwnuLists',
        setStoreInitUserData: 'setStoreInitUserData'
		}),
		// 1122
		initGet() {
			this.$get("/app/visitorInfo/_csrf").then((res) => {
				if (res.retCode === 1) {
					this.csrf = res.data._csrf;
					this.$loc_setItem("_csrf", this.csrf);
				}
			});
		},
		initPost(_csrf) {
			// 发送
			console.log(_csrf);
			let data = {
				_csrf: _csrf,
			};
			this.$post("/app/visitorInfo/_csrf", data).then((res) => {

			});
		},
		// 复制
		onCopy(e) {
			this.$toast({
              message:  "复制成功",
              duration: 1500,
              icon: "success",
            });
		},
		onError(e) {
			this.$toast({
              message: "复制错误",
              duration: 1500,
              icon: "close",
            });
		},
		// 关闭
		closebtn() {
			this.show = false;
		},
		checkemail() {
			if ( this.username.indexOf("@") >= 0 && /^[ a-z_A-Z0-9-\.!@#\$%\\\^&\*\)\(\+=\{\}\[\],~\·`\?:;|\r|\n|\\s]+$/.test(this.username)) {
			} else {
				this.accounthint = "邮箱格式错误 !";
			}
		},
		selcetcountry() {
			this.getnumfocus2();
			this.$router.push({
				path: "select_country",
				query: {
					from: "login",
					formType: this.formType
				},
			});
		},
		getTab(e) {
			this.activeTab = e;
			this.passwordstatus = true;
			this.eyestatus = false;
		},
		backfunlik() {
			this.$router.push({
				path: "/",
			});
		},
		callbackFn(item) {
			if (item.value === "ROUTER_P_EMAIL") {
				this.$router.push({
					path: "/changePassword",
					name: "changePassword",
				});
			} else if (item.value === "ROUTER_P_PHONE") {
				this.$router.push({
					path: "/changePassword_p",
					name: "changePassword_p",
				});
			}
			this.showname = false;
		},
		login() {
			console.log("登录--", this.userPhone);
			let _this = this;
			let versionnum = this.$loc_getItem("version");
			let versionval = "";
			if (versionnum) {
				versionval = versionnum;
			} else {
				versionval = "";
			}
			let loginmsg = {};

			if (this.tabNum == 0) {
				loginmsg.account = this.username;
				loginmsg.password = this.password;
				loginmsg.tab = this.tabNum;
			} else {
				loginmsg.tab = this.tabNum;
				loginmsg.account_phone = this.userPhone;
				loginmsg.password_phone = this.phonePassword;
				loginmsg.password_phonecode = this.userPhonecode;
			}

			this.$loc_setItem("accountinformation", JSON.stringify(loginmsg));
			if (Object.keys(this.checkbox).length) {
				this.$loc_setItem("remember", JSON.stringify(loginmsg));
			} else {
				localStorage.removeItem("remember");
			}
			var self = this;
			let iphoneinfo = JSON.parse(this.$loc_getItem("iphoneinfo")) || {};
			let registrationId = this.$loc_getItem("registrationId") || "";

			let loginType; //登录的模式
			let account;
			let password;
			let telcode;
			if (this.tabNum == 1) {
				//就是使用手机登录的时候
				account = this.userPhone;
				password = this.phonePassword;
				telcode = this.userPhonecode; //区号
				loginType = "byTel";
				if (!this.userPhonecode) {
					this.accounthint2 = "国家/地区代码不能为空!";
					return;
				}
				if (!account) {
					console.log("z------");
					this.accounthint2 = "手机号码为必填项!";
					return;
				}
				if (/^\d+$/.test(account) && account.indexOf(".") == -1) {
				} else {
					this.accounthint2 = "请输入真实的手机号码!";
					return;
				}
				// if (!this.ncountryname) {
				// 	this.accounthint2 = "手机号码为必填项!";
				// 	return;
				// }
				if (!password) {
					this.passwordhint2 = "密码为必填项!";
					return;
				}
			} else {
				// 邮箱登录
				account = this.username;
				password = this.password;
				loginType = "byEmail";
				telcode = "";
				if (!account) {
					this.accounthint = "电子邮箱地址为必填项!";
					return;
				}
				if (
					account.indexOf("@") >= 0 &&
					/^[ a-z_A-Z0-9-\.!@#\$%\\\^&\*\)\(\+=\{\}\[\]\/",'<>~\·`\?:;|\r|\n|\\s]+$/.test(
						account
					)
				) {
				} else {
					this.accounthint = "邮箱格式错误 !";
					return;
				}
				if (!password) {
					this.passwordhint = "密码为必填项!";
					return;
				}
			}

			let axiosdata = {
				loginName: account,
				password: password,
				telCountryCode: telcode,
				loginAgent: 2, //移动端是2,APP是3
				version: versionval,
				loginType: loginType,
				areaCodeCountry: this.areaCodeCountry,
			};
			if (iphoneinfo) {
				axiosdata.phoneFlag = iphoneinfo.uuid;
			}
			if (registrationId) {
				axiosdata.registrationId = registrationId;
			}
			this.$post("/user/loginUser", axiosdata)
				.then((response) => {
					if (response.retCode) {
						// 0728 账号禁用
						if (response.data.freezeId) {
							console.log("冻结 下一次发布");
							this.show = true;
							this.freezedata = response.data;
						} else {
							/**同步中文站登录信息需屏蔽一下代码**/
							let userinfo = response.data;
							let token = response.data.loginToken;
							let domain = this.$baseUrl;
							this.$parent.getUserHot();
							/**当前开发环境**/
							if (
								domain.indexOf("192.168.119") > -1 ||
								domain.indexOf("127.0.0.1") > -1
							) {
								self.loginSuccess(userinfo, token);
							} else {
								if (domain.indexOf("buildmost.cn") > -1) {
									domain = "https://www.buildmost.com";
								} else {
									domain = domain.replace(":801", "");
								}
								/**同步英文站登录信息***/
								this.$post(domain + "/user/loginUser", axiosdata).then(
									(res) => {
										if (res.retCode) {
											self.loginSuccess(userinfo, token);
										}
									}
								);
							}
						}
						// end
					} else {
						if (response.retMsg.indexOf("username") != -1) {
							self.accounthint = response.retMsg;
						} else {
							if (self.tabNum == 0) {
								self.passwordhint = response.retMsg;
							} else {
								self.passwordhint2 = response.retMsg;
							}
						}
					}
				})
				.catch(function (error) {
					console.log(error);
				});
		},
		loginSuccess(userinfo, token) {
			this.$loc_setItem("user", JSON.stringify(userinfo));
			this.$loc_setItem("token", token);
			this.$parent.updateLogin(true);
			this.$imSocket.config();
			this.setUserMwnuLists([])
			this.setStoreInitUserData(null)
			this.getUserPromission();
			if(this.formType == 'goBack') {
				this.$router.go(-1)
				return false;
			}
			if (this.$route.query.backname === "product_details") {
				this.$router.replace({
					path: "product_details",
					query: {
						proid: this.$route.query.proid,
						useid: this.$route.query.useid,
					},
				});
			} else {
				this.$router.push({ name: "index" });
			}
		},
		seepassword() {
			if (this.passwordstatus) {
				this.$refs.password.type = "text";
				this.passwordstatus = false;
			} else {
				this.$refs.password.type = "password";
				this.passwordstatus = true;
			}
		},
		seepasswordPhone() {
			if (this.passwordstatus) {
				this.$refs.phonePassword.type = "text";
				this.passwordstatus = false;
			} else {
				this.$refs.phonePassword.type = "password";
				this.passwordstatus = true;
			}
		},
		getpassfocus() {
			this.eyestatus = true;
			this.passwordhint = "";
		},
		getpassfocus2() {
			this.passwordhint2 = "";
		},
		getnumfocus2() {
			this.accounthint2 = "";
		},
		getacfocus() {
			this.accounthint = "";
		},
		onCountryCode() {
			if(this.userPhonecode) {
				const options = {
					threshold: 0.0,
					keys: ['id', 'name']
				}
				const fuse = new Fuse(this.CountryList, options);
				const searchLists = fuse.search(this.userPhonecode)
				if(searchLists && searchLists.length>1) {
					if (this.ncountryname) {
						const searchLists = fuse.search(this.ncountryname)
						this.ncountryname = searchLists[0].item.name;
						this.userPhonecode = searchLists[0].item.id;
						this.areaCodeCountry = searchLists[0].item.country_code;
					}else{
						this.ncountryname = searchLists[0].item.name;
						this.userPhonecode = searchLists[0].item.id;
						this.areaCodeCountry = searchLists[0].item.country_code;
					}
				} else if (searchLists && searchLists.length == 1) {
					this.ncountryname = searchLists[0].item.name;
					this.userPhonecode = searchLists[0].item.id;
					this.areaCodeCountry = searchLists[0].item.country_code;
				} else {
					this.ncountryname = ""
					this.userPhonecode = ""
					this.areaCodeCountry = ""
				}
			}
		}
	},
	watch: {
		userPhonecode(val) {
			let falg = false;
			this.CountryList.find((e, index) => {
				if (this.areaCodeCountry && e.id == val && e.country_code == this.areaCodeCountry) {
					this.ncountryname = this.CountryList[index].name;
					falg = true;
					return true
				}else if (e.id == val) {
					this.ncountryname = this.CountryList[index].name;
					falg = true;
				}
			});
			if (!falg) {
				this.ncountryname = "";
			}
		},
		username(val) {
			if (
				val.indexOf("@") >= 0 &&
				/^[ a-z_A-Z0-9-\.!@#\$%\\\^&\*\)\(\+=\{\}\[\]\/",'<>~\·`\?:;|\r|\n|\\s]+$/.test(
					val
				)
			) {
				this.accounthint = "";
			} else {
				this.accounthint = "邮箱格式错误 !";
			}
		},
		userPhone(val) {
			if (/^\d+$/.test(val) && val.indexOf(".") == -1) {
				this.accounthint2 = "";
			} else {
				this.accounthint2 = "请输入真实的手机号码!";
			}
		},
	},
	created() {},
	mounted() {
		eventBus.$on('onSelectCountryCode', (res) => {
			const { tabNum, code, country, countrycode } = res
			if (tabNum) {
				this.tabNum = tabNum;
			}
			if (code) {
				this.userPhonecode = code;
			}
			if (country) {
				this.ncountryname = country;
			}
			if (countrycode) {
				this.areaCodeCountry = countrycode
			}
		})
		// this.initGet(); //还有问题,暂不合并
		const { t, type } = this.$route.query;
		this.formType = type
		if (t) {
			this.t = t;
		}
		// var self = this;
		this.checkbox = [];
		var remember = JSON.parse(this.$loc_getItem("remember")) || "";
		if (remember) {
			this.username = remember.account || "";
			this.password = remember.password || "";
			/* if (remember.tab) {
				this.tabNum = remember.tab;
			} */
			this.userPhone = remember.account_phone || "";
			this.phonePassword = remember.password_phone || "";
			this.userPhonecode = remember.password_phonecode || 86;
			this.checkbox = [1];
		} else {
			this.userPhonecode = 86
		}
		let loginstauts = this.$loc_getItem("token");
		if (loginstauts) {
			this.$router.push({
				path: "/",
			});
		}
		if (this.$route.query.tabNum) {
			this.tabNum = this.$route.query.tabNum;
		}
		if (this.$route.query.code) {
			this.userPhonecode = this.$route.query.code;
		}
		if (this.$route.query.country) {
			this.ncountryname = this.$route.query.country;
		}
	},
};
</script>
<style lang='less' scoped>
.maincode {
	width: 100% !important;
	border-right: 1px solid #e6e6e6 !important;
}
.general_input {
	padding: 0.2rem 0;
	border-bottom: 1px solid #e6e6e6;
	font-size: 0.26rem;
}
.general_input input {
	border: 0;
	width: 100%;
	padding: 0 .15rem;
}
.selectcountry {
	padding: 0.2rem 0;
	.icon-next {
		margin-top: -0.32rem;
	}
}
.loginbg {
	height: 3.65rem;
	background-image: url("../image/new-icon/login_bg.png");
	background-repeat: no-repeat;
	background-size: 100% 100%;
	.text {
		font-family: "思源黑体";
		font-size: .8rem;
		color: #fff;
		padding-left: .6rem;
		padding-top: .8rem;
	}
}
.loginbox {
	border-radius: 0.2rem 0.2rem 0rem 0rem;
	padding: .6rem 0.72rem 0rem;
	.mar_t(-0.8rem);
	background: #fff;
	.logintilte {
		font-size: 0.4rem;
		font-weight: bold;
		margin-bottom: 0.4rem;
	}
	.logininp input {
		border: none;
		border-bottom: 1px solid #e6e6e6;
		padding-bottom: 0.23rem;
		width: 100%;
	}
	.password {
		position: relative;
		img {
			width: 0.41rem;
			height: 0.25rem;
			position: absolute;
			right: 0.07rem;
			bottom: 0.23rem;
		}
	}
	.loginrow {
		margin-top: 0.39rem;
	}
	.loginbtn {
		.mar_t(0.57rem);
		div {
			width: 6rem;
			height: 1.1rem;
			@gradient_blue();
			text-align: center;
			line-height: 1.1rem;
			color: #fff;
			font-size: 0.36rem;
			border-radius: 0.04rem;
			display: inline-block;
		}
	}
  @media screen and (max-width: 280px) {
    .loginbtn {
      div {
        width: 5rem;
      }
    }
  }
	.regs {
		.fonts(0.3rem);
		margin-top: 0.2rem;
	}
}
.mar_b80 {
	.mar_b(0.8rem);
}
.forget {
	margin-top: 2px;
}
.accounthint {
	margin: 0.25rem 0 0.46rem;
}
.passwordhint {
	margin: 0.25rem 0 0.4rem;
}
.pos_icon {
	position: absolute;
	top: 0.3rem;
	left: 0.2rem;
	width: 0.8rem;
	height: 0.8rem;
	border-radius: 0.5rem;
	background: #9697993b;
	display: flex;
	align-items: center;
	justify-content: center;
}
.pos_icon span {
	font-size: 0.65rem;
	color: white;
	font-weight: bold;
}
// .login_botn {
// 	padding-top: 20%;
// }
.clwe_word {
	display: flex;
	align-items: center;
	justify-content: center;
}
// 0622 冻结
.freeze-open /deep/ .van-popup {
	width: 80%;
	border-radius: 0.1rem;
}
.freeze-box {
	padding: 0.3rem;
	.freeze {
		margin: 0 auto;
		width: 0.3rem;
		height: 0.3rem;
		display: block;
	}
	.freeze-top {
		margin: 0.2rem 0;
	}
}
.freeze-box h3 {
	text-align: center;
}
// 2
.freeze-box {
	font-size: 0.28rem;
	h3 {
		font-weight: 800;
	}
	.conten {
		margin: 0.2rem 0;
		line-height: 0.34rem;
	}
	.Confirmbtn {
		display: flex;
		justify-content: center;
		button {
			width: 2.1rem;
			padding: 0.2rem 0;
			background: linear-gradient(180deg, #0066ff 0%, #0099ff 100%);
			border: none;
			font-size: 0.26rem;
			color: #ffffff;
			border-radius: 4px;
		}
	}
}
.back-home-text {
	font-size: .3rem;
	margin-top: .16rem;
	justify-content: center;
}
</style>
